<template>
	<view class="container">
		<Navigator2 :title="$t('device.cloneMyVoice')"></Navigator2>
		<view class="top_tips">
			<image src="/static/warn_yellow.png"></image>
			<view class="rest_times">{{ $t('device.remainingModificationTimes') }} {{customVoiceRestTimes}}/10</view>
		</view>
		<view class="voice_info">
			<view class="voice_info_item">
				<text>{{ $t('device.voiceName') }}<text style="color: #E34D59;margin-left: 6px;">*</text></text>
				<input :placeholder="$t('device.pleaseEnterVoiceName')" placeholder-style="color: #BDBDBD;" v-model="voiceName" />
			</view>
		</view>
		<view class="agreement">
			<image :src="agreementCheck ? '/static/radio_2.png' : '/static/radio_1.png'" @click="agreementCheck = !agreementCheck"></image>
			<text @click="agreementCheck = !agreementCheck">{{ $t('device.iHaveReadAndAgreed') }}</text>
			<a href="#" @click="naviToCloneVoiceAgreementPage">{{ $t('device.privacyAgreement') }}</a>
		</view>
		<view class="beginclone" @click="beginclone">{{ $t('device.beginClone') }}</view><!-- 开始克隆 -->
		
		<!-- 朗读弹框 -->
		<view class="modal-overlay" v-if="showModal" @click="closeModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<image class="close-btn" src="/static/clone_x.png" @click="closeModal"></image>
				</view>
				<view class="modal-title">{{ $t('device.pleaseReadTheFollowingContent') }}</view>
				<view class="modal-text">
					{{ $t('device.aiIsChangingOurLifestyle') }}
				</view>
				<view v-if="recorded" class="rec-info">
					<view class="rec-title">
						<text>{{ $t('device.recordedContent') }}</text>
						<text @click="rerecord">{{ $t('device.rerecord') }}</text>
					</view>
					<view class="rec-content" @click="playVoice" :class="{playing: isPlaying}">
						<image src="/static/clone_voice.png" :class="{playing: isPlaying}"></image>
						<text style="margin-left: 12px;">{{isPlaying ? $t('device.playing') : $t('device.clickPlay')}}</text>
						<text>{{duration}}s</text>
					</view>
				</view>
				<view v-if="recorded" class="complete-btn" @click="cloneVoice">{{ $t('device.complete') }}</view>
				<view v-if="!recorded" class="record-btn" @touchstart="startRecord" @touchend="stopRecord">
					<image src="/static/clone_mic.png"></image>
					<text>{{ $t('device.pressAndSpeak') }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import api from '@/js/api.js'
	import permision from '@/js_sdk/wa-permission/permission.js'
	import Navigator2 from '@/components/Navigator2.vue'
	
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	
	innerAudioContext.autoplay = true;
	
	export default {
			data() {
					return {
						deviceId: '',
						voiceName: '',
						voiceDesc: '',
						voicePath: '',
						agreementCheck: false,
						showModal: false,
						recorded: false,
						duration: 0,
						customVoiceRestTimes: 0,
						isPlaying: false,
						recordStartTime: 0
					}
				},
			onLoad(param) {
					this.deviceId = param.deviceId
					this.customVoiceRestTimes = param.customVoiceRestTimes
					let self = this;
					recorderManager.onStop(function (res) {
						console.log('recorder stop' + JSON.stringify(res))
						self.voicePath = res.tempFilePath
						self.duration = Math.round(res.duration / 1000)
					});
					
					// 监听音频播放结束
					innerAudioContext.onEnded(() => {
						self.isPlaying = false
					})
					
					// 监听音频播放错误
					innerAudioContext.onError(() => {
						self.isPlaying = false
					})
				},
			onHide() {
				innerAudioContext.stop()
			},
			methods: {
				async beginclone() {
					// 判断设备是苹果还是安卓
					const systemInfo = uni.getSystemInfoSync()
					if (systemInfo.platform == 'ios') {
						permision.judgeIosPermission("record").then(res => {
							if (res) {
								// 权限已授权
							} else {
								// 权限未授权
								uni.showToast({
									icon: 'none',
									title: this.$t('device.pleaseAuthorizeRecordPermission'),
									duration: 2000
								})
								return
							}
						})
					} else {
						var result = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO')
						var strStatus
						if (result == 1) {
							strStatus = this.$t('device.authorized')
						} else if (result == 0) {
							strStatus = this.$t('device.notAuthorized')
						} else {
							strStatus = this.$t('device.permanentlyRejectedPermission')
						}
						if (result != 1) {
							uni.showModal({
								content: this.$t('device.microphonePermission') + strStatus,
								showCancel: false
							})
						}
					}

					if (this.voiceName == null || this.voiceName == '' || this.voiceName == undefined) {
						uni.showToast({
							icon: 'none',
							title: this.$t('device.voiceNameCannotBeEmpty'),
							duration: 2000
						})
						return
					}
					if (!this.agreementCheck) {
						uni.showToast({
							icon: 'none',
							title: this.$t('device.pleaseCheckThePrivacyAgreement'),
							duration: 2000
						})
						return
					}
					// 显示朗读弹框
					this.showModal = true
				},
				closeModal() {
					this.showModal = false
				},
				startRecord() {
					console.log('开始录音')
					this.recordStartTime = Date.now()
					recorderManager.start({format:'wav'})

					// uni.authorize({
					// 	scope: 'scope.record',
					// 	success: function () {
					// 		console.log('录音权限授权成功')
					// 		recorderManager.start({format:'wav'})
					// 	},
					// 	fail: function () {
					// 		console.log('录音权限授权失败')
					// 		uni.showModal({
					// 			content: '检测到您没打开录音功能权限，是否去设置打开？',
					// 			confirmText: "确认",
					// 			cancelText: '取消',
					// 			success(res) {
					// 				uni.openSetting({
					// 					success(res) {
					// 						console.log(res);
					// 					},
					// 					fail(res) {
					// 						uni.showToast({
					// 							title: '打开授权设置失败',
					// 							icon: 'none'
					// 						})
					// 					}
					// 				});
					// 			}
					// 		})
					// 	}
					// })
				},
				stopRecord() {
					console.log('停止录音')
					recorderManager.stop()
					
					// 计算录音时长
					const recordEndTime = Date.now()
					const calculatedDuration = Math.round((recordEndTime - this.recordStartTime) / 1000)
					
					setTimeout(() => {
						this.recorded = true
						// 如果 res.duration 不存在或为0，使用计算的时长
						if (!this.duration || this.duration === 0) {
							this.duration = calculatedDuration
						}
					}, 1000)
				},
				playVoice() {
					console.log('播放录音')
					
					if (this.voicePath) {
						if (this.isPlaying) {
							// 如果正在播放，则停止播放
							innerAudioContext.stop()
							this.isPlaying = false
						} else {
							// 开始播放
							innerAudioContext.src = this.voicePath
							innerAudioContext.play()
							this.isPlaying = true
						}
					}
				},
				rerecord() {
					innerAudioContext.stop()
					this.recorded = false
					this.voicePath = ''
					innerAudioContext.src = ''
					this.isPlaying = false
				},
				cloneVoice() {
					// 保存音色
					api.saveCustomVoice(this.deviceId, this.voiceName, this.voiceDesc, this.voicePath).then(res => {
						console.log('saveCustomVoice res:', res)
						uni.navigateBack({delta: 1})
					}).catch(err => {
						console.error('保存音色失败:', err)
						uni.showToast({
							icon: 'none',
							title: this.$t('device.saveFailed, please try again'),
							duration: 2000
						})
					})
				},
				naviToCloneVoiceAgreementPage() {
					uni.navigateTo({
						url: `/pages/device/clonevoiceagreement`
					})
				}
			},
		components: {
			Navigator2
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: #F0F2F5;
	}
	
	.top_tips {
		border-top: 1px solid #F3F4F6;
		border-bottom: 1px solid #E7E7E7;
		display: flex;
		align-items: center;
		height: 22px;
		padding: 12px 16px;
		background-color: #FFFBE8;
		image {
			width: 19.25px;
			height: 19.25px;
		}
		.rest_times {
			margin-left: 10px;
			color: #ED6A0C;
			font-size: 14px;
		}
	}

	.voice_info_item {
		display: flex;
		align-items: center;
		height: 48px;
		background-color: #FFFFFF;
		border-bottom: 1px solid #E7E7E7;
		text {
			width: 100px;
			margin-left: 16px;
			font-size: 16px;
			color: #000000;
		}
		input {
			font-size: 16px;
			width: 60%;
		}
	}
	
	.agreement {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		margin-left: 20px;
		margin-right: 20px;
		margin-bottom: 20px;
		text-align: center;
		position: fixed;
		bottom: 60px;
		width: 90%;
		z-index: 999; /* 防止被覆盖 */
		image {
			width: 21px;
			height: 21px;
		}
		text {
			margin-left: 10px;
		}
		a {
			color: #7A68F7;
			text-decoration: none;
		}
	}
	
	.beginclone {
		font-size: 14px;
		margin-left: 20px;
		margin-right: 20px;
		margin-bottom: 20px;
		border-radius: 8px;
		color: white;
		margin-top: 20px;
		background-color: #0256FF;
		text-align: center;
		height: 45px;
		line-height: 45px;
		position: fixed;
		bottom: 0;
		width: 90%;
		z-index: 999; /* 防止被覆盖 */
	}
	
	/* 弹框样式 */
	.modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.modal-content {
		width: 78%;
		max-width: 400px;
		background-color: white;
		border-radius: 12px;
		padding: 20px;
		position: relative;
	}
	
	.modal-header {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 10px;
		image {
			width: 15px;
			height: 15.11px;
		}
	}
	
	.close-btn {
		font-size: 24px;
		color: #999;
		cursor: pointer;
		width: 30px;
		height: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.modal-title {
		color: #4B5563;
		font-size: 16px;
		margin-left: 10px;
		margin-bottom: 12px;
	}
	
	.modal-text {
		font-size: 16px;
		line-height: 24px;
		color: #374151;
		border-radius: 8px;
		background: #F6F6F6;
		padding: 12px;
		margin: 0 10px 30px 10px;
		text-align: justify;
	}
	
	.record-btn {
		background-color: #0256FF;
		color: white;
		border-radius: 8px;
		height: 48px;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10px;
		font-size: 16px;
		cursor: pointer;
		user-select: none;
		margin-bottom: 16px;
		
		image {
			width: 11px;
			height: 16px;
		}
		
		&:active {
			border-radius: 8px;
			background-color: #2E5DCC;
		}
	}
	
	.complete-btn {
		background-color: #0256FF;
		color: white;
		border-radius: 8px;
		height: 48px;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10px;
		font-size: 16px;
		cursor: pointer;
		user-select: none;
		margin-bottom: 16px;
		
		&:active {
			border-radius: 8px;
			background-color: #2E5DCC;
		}
	}
	
	.rec-info {
		margin: 5px 10px;
		.rec-title {
			display: flex;
			height: 24px;
			margin-bottom: 6px;
			text:first-child {
				color: #4B5563;
				font-size: 16px;
			}
			text:last-child {
				margin-left: auto;
				color: #3B82F6;
				font-size: 16px;
			}
		}
		.rec-content {
			display: flex;
			align-items: center;
			color: #FFFFFF;
			font-size: 16px;
			padding: 8px 12px;
			border-radius: 8px;
			margin-bottom: 30px;
			background: linear-gradient(97deg, #73BDFF -114%, #3F8DFF 98%);
			box-shadow: 0px 4px 8px 0px rgba(95, 163, 255, 0.3);
			transition: all 0.3s ease;
			
			&.playing {
				background: linear-gradient(97deg, #FF73BD -114%, #FF3F8D 98%);
				box-shadow: 0px 4px 8px 0px rgba(255, 95, 163, 0.3);
				animation: pulse 1.5s infinite;
			}
			
			image {
				width: 16.25px;
				height: 15.2px;
				transition: transform 0.3s ease;
				
				&.playing {
					animation: bounce 0.6s infinite alternate;
				}
			}
			
			text:last-child {
				margin-left: auto;
				margin-right: 3px;
			}
		}
		
		@keyframes pulse {
			0% {
				transform: scale(1);
				opacity: 1;
			}
			50% {
				transform: scale(1.02);
				opacity: 0.9;
			}
			100% {
				transform: scale(1);
				opacity: 1;
			}
		}
		
		@keyframes bounce {
			0% {
				transform: translateY(0) scale(1);
			}
			100% {
				transform: translateY(-2px) scale(1.1);
			}
		}
	}
</style>
